<?php 

class Helper_Grid extends Zend_Controller_Action_Helper_Abstract {
	
	// wyszło jak zwykle...
	// przerobićzeby nie było echo ; dla przejżystości echo tylko w kontrolerze powinno być - a die w validacji.
	
	// direct($class,$where,$join, $raw,$adapter,$group,$having,$fields,$order)
	
	public function direct(My_Model $class,$where = null,$join = null, 
		$raw = false, $adapter = null,$group = null,$having = null,$fields = null,$order = null,$log = false){
		
		$rq = $this->getRequest();
    	
        list($sort,$dir,$start,$limit) = array(
        	$rq->getParam('sort'),$rq->getParam('dir'),
        	$rq->getParam('start'),$rq->getParam('limit')
		);
		$sort = $sort ? $sort.($dir?' '.$dir:''):null;
		
		if($order && $sort){// sortowanie po wielu kolumnach
			if(is_array($order))array_unshift($order,$sort);// org push??
			else $order = array($order,$sort);
		} else $order = $sort;
		
		if($where==null)$where = Utils::createWhereStatement($rq->getParam('where'));
		
		$q = $class->q($where, $join,$order, $limit,intval($start), $adapter,$group,$having,$fields,$log);
		
	    $total = $limit ? $class->q($where,$join,null,null,0,$adapter,$group)->rowCount() : $q->rowCount();
	    
		echo $raw ? $q : json_encode(array("rows"=>$q->fetchAll(),"total"=>$total,"success"=>true));	
	}
	
	public function _(array $c){
		
		$k = function ($key,$def = null) use ($c){
			return array_key_exists($key, $c) ? $c[$key] : ($def == '!' ? 
				Validation::react('Nie określono klasy modelu.') : $def);
		};
		
		$class = $k('class','!');
		$class = is_string($class) ? new $class() : $class;
		
		$where = $k('where');
		
		$joinClass = $k('joinClass');

		$join= $joinClass ? $this->joinClass($joinClass,$class) : 
			$k('joins') ? 
				array('joins'=>$k('joins')) : $k('join');
		
		$adapter = $k('adapter');
		$group = $k('group');
		$having = $k('having');
		$fields = $k('fields');
		$order = $k('order');
		$raw = $k('raw',false);
		$log = $k('log',false);
		
		return $this->direct($class,$where,$join, $raw, $adapter,$group,$having,$fields,$order,$log);
	}
	
	private function joinClass($join,$mainClass){
		$class = get_class($mainClass);
		$joins = array();

		foreach($join as $joe){
				
			if(strpos($joe,'=>')!==false){
				$parts = explode('=>',$joe);
				list($joe,$alias) = $parts;
				$jClass = new $joe();
				$tName = array($alias=>$jClass->info('name'));
			} else {
				$jClass = new $joe();
				$tName = $jClass->info('name');
				$alias = $tName;
			}
			
			$ref = $jClass->getReference($class);
			$where = 'd.'.$ref['columns'][0].' = '.$alias.'.'.$ref['refColumns'][0];
			
			array_push($joins,array(
				$tName,$where,array(),'left'
			));
		}
		
		return array('joins'=>$joins);
	}
	
	
}

?>